<!-- eslint-disable vue/multi-word-component-names -->
 <template>
  <div>
    <div style="margin-bottom: 5px; text-align: center;">
      <el-button 
        type="primary" 
        :icon="Plus" 
        circle 
        style="margin-left: 5px;" 
        @click="add()"
        v-if="hasAuth('system:notice-save')"
      />
      
      <el-button 
        type="danger" 
        :icon="Delete" 
        circle 
        style="margin-left: 5px;" 
        @click="delHandle(null)"
        v-if="hasAuth('system:notice-delete')" 
        :disabled="delBtnStatus"
      />
    </div>
    
    <el-table 
      ref="multipleTableRef" 
      :data="tableData" 
      tooltip-effect="dark" 
      border 
      style="width: 100%" 
      stripe
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />

      <el-table-column prop="carousel" label="轮播图展示">
        <template #default="scope">
          <img :src="scope.row.carousel" width="800" height="200" />
        </template>
      </el-table-column>

      <el-table-column fixed="right" label="操作" width="300px" prop="operate">
        <template #default="scope">
          <el-button 
            type="primary" 
            :icon="Edit" 
            circle 
            @click="mod(scope.row)"
            style="margin-left: 5px;" 
            v-if="hasAuth('system:notice-update')"
          />
          
          <el-button 
            type="danger" 
            :icon="Delete" 
            circle 
            style="margin-left: 5px;"
            @click="delHandle(scope.row.id)" 
            v-if="hasAuth('system:notice-delete')"
          />
        </template>
      </el-table-column>
    </el-table>
    
    <el-pagination 
      @size-change="handleSizeChange" 
      @current-change="handleCurrentChange" 
      :current-page="pageNum"
      :page-size="pageSize" 
      :page-sizes="[5, 10, 50, 100]" 
      background
      layout="total,sizes,prev, pager, next,jumper" 
      :total="total"
    />
    
    <el-dialog 
      v-model="centerDialogVisible" 
      title="轮播图增改表单" 
      width="50%" 
      center
    >
      <el-form 
        :model="form" 
        :rules="rules" 
        ref="formRef" 
        label-width="100px" 
        style="width: 800px; margin: 10px auto"
        enctype="multipart/form-data"
      >
        <el-form-item label="轮播图展示" prop="carousel">
          <el-upload 
            action="#" 
            list-type="picture-card" 
            :auto-upload="false" 
            :on-exceed="handleExceed"
            accept="image/*" 
            :on-change="submitUpload" 
            :file-list="fileList" 
            :limit="1"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="centerDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
// eslint-disable-next-line vue/multi-word-component-names
import { ref, reactive, onMounted, computed } from 'vue'
import { Plus, Delete, Edit } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Store } from '@/store/index'
import api from '@/axios/index'

// 获取 store 实例
const store = Store()

// refs
const multipleTableRef = ref()
const formRef = ref()

// 数据响应式
const pageSize = ref(5)
const pageNum = ref(1)
const total = ref(0)
const tableData = ref([])
const delBtnStatus = ref(true)
const centerDialogVisible = ref(false)
const multipleSelection = ref([])
const fileList = ref([])

const form = reactive({
  id: "",
  carousel: ""
})

const rules = {
  carousel: [
    { required: true, message: '请上传轮播图展示图片', trigger: 'change' }
  ]
}

// 计算属性
const hasAuth = computed(() => {
  return function (perm) {
    return store.permList.includes(perm)
  }
})

// 方法
const add = () => {
  centerDialogVisible.value = true
  resetForm()
}

const mod = (row) => {
  // 赋值到表单
  api.get("/carousel/info/" + row.id).then((res) => {
    Object.assign(form, res.data)

    if (form.carousel != "") {
      fileList.value = []
      fileList.value.push({
        url: form.carousel,
      })
    }
    form.update = 1
    centerDialogVisible.value = true
  })
}

const save = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      if (form.id) {
        doMod() // 完成上传后执行 doMod 函数
      } else {
        doSave()
      }
    } else {
      ElMessage({
        message: "请填写正确数据",
        type: "error",
      })
      return false
    }
  })
}

const doSave = () => {
  api.post("/carousel/save", form)
    
    .then((res) => {
      console.log(res)
      if (res.code == 200) {
        ElMessage({
          message: "操作成功！",
          type: "success",
        })
        centerDialogVisible.value = false
        loadPost()
        resetForm()
      } else {
        ElMessage({
          message: res.msg,
          type: "error",
        })
      }
    })
}

const doMod = () => {
  api.post("/carousel/update", form)
    
    .then((res) => {
      console.log(res)
      if (res.code == 200) {
        ElMessage({
          message: "操作成功！",
          type: "success",
        })
        centerDialogVisible.value = false
        loadPost()
        resetForm()
      } else {
        ElMessage({
          message: res.msg,
          type: "error",
        })
      }
    })
}

const handleExceed = (files) => {
  console.log(files)
  ElMessage.error("只能上传一张图片")
}

const submitUpload = (file) => {
  const config = {
    headers: {}
  }
  let fd = new FormData()
  fd.append("file", file.raw)
  fd.append("name", file.name)

  api.post("/file/upload", fd, config).then((res) => {
    console.log(res)
    if (res.code == 200) {
      form.carousel = res.data.url
      // 存储返回的数据
      ElMessage({
        message: "上传成功！",
        type: "success"
      })
    } else {
      ElMessage({
        message: "上传失败",
        type: "error"
      })
    }
  })
}

const resetForm = () => {
  Object.assign(form, {
    id: "",
    carousel: null,
  })

  fileList.value = []
}

const handleSizeChange = (val) => {
  console.log(`每页 ${val} 条`)
  pageNum.value = 1
  pageSize.value = val
  loadPost()
}

const handleCurrentChange = (val) => {
  console.log(`当前页: ${val}`)
  pageNum.value = val
  loadPost()
}

const loadPost = () => {
  api.post("/carousel/listPage", {
    pageSize: pageSize.value,
    pageNum: pageNum.value,
    param: {}
  })
    .then((res) => {
      console.log(res)
      if (res.code == 200) {
        tableData.value = res.data
        if (res.length == 0 && pageNum.value != 1) {
          pageNum.value = 1
          loadPost()
        }
        total.value = res.total
      } else {
        ElMessage({
          message: "数据查询失败",
          type: "warning",
        })
      }
    })
}

const delHandle = (id) => {
  console.log(id)
  var ids = []
  if (id) {
    ids.push(id)
  } else {
    multipleSelection.value.forEach((row) => {
      ids.push(row.id)
    })
  }
  
  ElMessageBox.confirm("将删除轮播图一切有关数据， 是否继续?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    api.post("/carousel/deleteBatch", ids, {
      headers: {
        "Content-Type": "application/json;charset=UTF-8",
      },
    }).then((res) => {
      console.log(res)
      ElMessage({
        showClose: true,
        message: "恭喜你，操作成功",
        type: "success",
      })
      loadPost()
    }).catch((err) => {
      console.error(err)
      ElMessage({
        showClose: true,
        message: "操作失败，请重试",
        type: "error",
      })
    })
  }).catch(() => {
    ElMessage({
      showClose: true,
      message: "已取消操作",
      type: "info",
    })
  })
}
const handleSelectionChange = (val) => {
  multipleSelection.value = val
  delBtnStatus.value = val.length == 0
}

// 生命周期
onMounted(() => {
  loadPost()
})
</script>

<style scoped>
.el-pagination {
    display: flex;
    justify-content: center;
    margin-top: 20px;
}
</style>